<?php
class CustStockOutReturnsController extends AppController {
    var $name = 'CustStockOutReturns';

    var $pageTitle = 'Return Product from Stock out back to Inventory';

    var $viewPath = 'customers/returns/stock_out_returns';

    /**
     * CSoRH => 'CustStockOutReturnHead
     * CSoR => 'CustStockOutReturn
     * @var array Class Model ที่ใช้
     */
    var $uses = array('CSoRH', 'CSoR', 'CustStockOutHead', 'CustStockOut', 'CustProductSite', 'ProductSerial', 'Customer', 'Site', 'User', 'RunningNo', 'CustLocation', 'CSoRR');

    var $paginate = array(
            'CSoRH' => array(
                            'order' => 'CSoRH.id DESC'
            )
    );

    var $components = array('Email');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'main_cust_returns');
        $this->set('tabMenu', 'tabmenus/customer/returns');

        $this->_checkPrintView();
    }

    /**
     * @param <type> $csoh_id ถ้ามีจะแสดงเฉพาะ return ที่มาจาก CustStockOutHead ที่ระบุ (มาจากหน้า cust_stocks_out
     */
    function display() {
        parent::display('CSoRH');
        $this->paginate['CSoRH']['contain'] = array('CustStockOutHead', 'Supplier');
        if (!empty($this->passedArgs['cust_stock_out_head_id'])) {
            $this->data['CSoRH']['cust_stock_out_head_id'] = $this->passedArgs['cust_stock_out_head_id'];
        }

        $this->_checkSite('CSoRH');

        $this->_paging('CSoRH');
    }


    function save() {
        $is_success = true;
        $csorh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            if (!empty($this->data['CSoRH']['id'])) {
                $this->CSoRH->id = $this->data['CSoRH']['id'];
                $is_success = $this->CSoRH->saveField('remark', $this->data['CSoRH']['remark']);
                $is_success &= $this->CSoRH->saveField('collector_id', $this->Auth->user('id'));
            }
        }

        if ($is_success) {
            $csorh_id = $this->CSoRH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['CSoR'] = null;
        $this->setAction('view', $csorh_id);
    }

    function _save_return() {
        $csorh_id = null;

        $is_success = true;

        // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
        $this->adjustRowIndex($this->data['CSoR']);

        // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
        if(count($this->data['CSoR']) == 0) {
            $this->Session->setFlash("You didn't have any return product!", 'flash/fail');
            $is_success = false;
            unset($this->data);
        } else {
            $this->CSoRH->query("BEGIN");
            $collector_id = $this->Auth->user('id');
            $customer_id = $this->Auth->user('customer_id');
            $site_id = $this->Auth->user('site_id');

            // กำหนดข้อมูล Cust Stock out Return Head
            // Generate return no
            $this->Customer->id = $this->Auth->user('customer_id');
            $cust_no = $this->Customer->field('cust_no');
            $this->Site->id = $this->Auth->user('site_id');
            $site_no = $this->Site->field('site_no');
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::CUST_STOCK_OUT_RETURN_TYPE, $year, $customer_id);
            $this->data['CSoRH']['return_no'] = $cust_no . '-' . $site_no . '-' . RunningNo::CUST_STOCK_OUT_RETURN_TYPE . '-' . $year . $runno;
            $this->data['CSoRH']['customer_id'] = $this->Auth->user('customer_id');
            $this->data['CSoRH']['site_id'] = $this->Auth->user('site_id');
            $this->data['CSoRH']['collector_id'] = $this->Auth->user('id');

            if($this->CSoRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                // update CustStockOutHead ว่ามีการ Return
                $this->CustStockOutHead->id = $this->data['CSoRH']['cust_stock_out_head_id'];
                $this->CustStockOutHead->saveField('is_cust_stock_out_return', true);

                $csorh_id = $this->CSoRH->id;
                foreach ($this->data['CSoR'] as $cSoR) {
                    // Update Cust Product Site current stock
                    $return_qty = $cSoR['return_qty'];
                    $this->CustProductSite->id = $cSoR['cust_product_site_id'];
                    $is_success &= $this->CustProductSite->addCurrentStock($this->CustProductSite->id, $return_qty);

                    // Update CustStockOut ยอดที่มีการ Stock out เหลืออยู่
                    $this->CustStockOut->id = $cSoR['cust_stock_out_id'];
                    $old_return_qty = $this->CustStockOut->field('return_qty');
                    $this->CustStockOut->saveField('return_qty', $old_return_qty + $return_qty);
                    $net_stock_out_qty = $this->CustStockOut->field('net_stock_out_qty');
                    $this->CustStockOut->saveField('net_stock_out_qty', $net_stock_out_qty - $return_qty);

                    // ดึงรายการ cust_stock_out_return
                    $this->CSoR->contain();
                    $_csor = $this->CSoR->find('first', array(
                            'conditions' => array(
                                    'CSoR.product_id' => $cSoR['product_id'],
                                    'cust_stock_out_return_head_id' => $csorh_id
                            ))
                    );

                    $PSs = array();
                    // ถ้าเป็น IE 6 ไม่ส่ง Product Serial มา
                    $is_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== FALSE);
                    if ($is_ie6 || empty($cSoR['ProductSerial'])) {
                        $this->ProductSerial->contain();
                        $PSs = $this->ProductSerial->find('all', array(
                                'conditions' => array(
                                        'cust_product_site_id' => $cSoR['cust_product_site_id'],
                                        'cust_stock_out_id' => $cSoR['cust_stock_out_id'],
                                        'cust_stock_out_type' => CustStockOut::STOCK_OUT_TYPE,
                                        'is_active_flag' => true,
                                ),
                                'order' => array('stock_out_priority ASC'),
                                'limit' => $return_qty
                                )
                        );
                    } else {
                        $PSs = $cSoR['ProductSerial'];
                    }

                    foreach ($PSs as $_ps) {
                        if ($is_ie6 || isset($_ps['return'])) {
                            $this->ProductSerial->copyProductSerial($is_ie6? $_ps['ProductSerial']['id']: $_ps['id'], $_csor['CSoR']['id'], CSoR::CUST_STOCK_IN_TYPE);
                        }
                    }
                }
                // เช็คว่า ถ้า return ทั้งหมดที่มีใน Stock out no. นี้ ติ๊กใบ stock out เป็น complete return
                $this->CustStockOut->contain();
                $all = $this->CustStockOut->find('first', array(
                        'fields' => 'SUM(net_stock_out_qty) net_qty',
                        'conditions' => array('cust_stock_out_head_id' => $this->CustStockOutHead->id)
                ));
                if ($all[0]['net_qty'] == 0) {
                    $this->CustStockOutHead->saveField('is_complete_return', true);
                }
            } else {
                $is_success = false;
            }

            if ($is_success) {
                $this->CSoRH->query("COMMIT");
                $csorh_id = $this->CSoRH->id;
                $this->_sendEmail($csorh_id);
            } else {
                $this->CSoRH->query("ROLLBACK");
            }
        }
        return $is_success;
    }

    function _sendEmail($csorh_id) {
        $userName = $this->Auth->user('name');
        $this->Customer->id = $this->Auth->user('customer_id');
        $customerName = $this->Customer->field('name');
        $this->Site->id = $this->Auth->user('site_id');
        $siteName = $this->Site->field('name');

        $this->Email->from    = "{$userName} {$customerName} {$siteName} <{$this->Auth->user('email')}>";
        $this->Email->to      = $this->requestAction('system_preferences/get/contact_email');
        //$this->Email->subject = $this->requestAction('system_preferences/get/site_title') . ' : Customer Stock In';
        $this->CSoRH->id = $csorh_id;
        $this->Email->subject = 'VMI : Customer Stock out return ' . $this->CSoRH->field('return_no');
        $this->Email->template = 'customer/return/cust_stock_out_return';
        $this->Email->sendAs  = 'html';
        //$this->Email->delivery  = 'debug';

        $this->set('userName', $userName);
        $this->set('customerName', $customerName);
        $this->set('siteName', $siteName);
        $this->set('csorh_id', $csorh_id);
        $this->Email->send();

        //debug( $this->Session->read( 'Message.email' ) );
    }

    function view($id = null) {
        // mode edit
        if ($id != null) {
            $this->CSoRH->contain(array('Customer', 'Site', 'CustStockOutHead', 'Supplier', 'CSoRR',
                    'CSoR' => array('Product' => array('part_no', 'supplier_part_no', 'text', 'Unit'), 'CustProductSite' => array('stock_code'))));
            $this->data = $this->CSoRH->findById($id);

            $this->_neighbors($id, $this->CSoRH, array('fields' => array('id', 'return_no')));
            $this->set('mode', 'edit');
        } else {
            $this->set('cSoHs', $this->CustStockOutHead->find('list', array(
                    'conditions' => array(
                            'CustStockOutHead.site_id' => $this->Auth->user('site_id'),
                            'CustStockOutHead.is_invoiced' => false,
//                            'CustStockOutHead.is_cust_stock_out_return' => false,
                            'CustStockOutHead.is_complete_return' => false
                    ),
                    'order' => 'id DESC'
                    )
                    )
            );
            $this->set('custLocations', $this->CustLocation->find('list', array('conditions' => array('site_id' => $this->Auth->user('site_id')))));
            $this->set('reasons', $this->CSoRR->find('list', array('conditions' => array('site_id' => $this->Auth->user('site_id')))));
            $this->set('return_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->data = $this->CSoRH->findForPrintById($id);
    }

    function json_find_by_part_no_cust_stock_out_head_id() {
        $this->RequestHandler->setContent('json');
        $this->layout = 'ajax';

        // ค้นหาข้อมูลโดย part no และ dispatch id
        $this->CustStockOut->contain(array('Product' => array('Unit'), 'CustProductSite'));
        $data = $this->CustStockOut->find('first', array('conditions' => array(
                        'OR' => array(
                                'Product.part_no' => $this->data['part_no'],
                                'Product.supplier_part_no' => $this->data['part_no'],
                                'CustProductSite.stock_code' => $this->data['part_no'],
                        ),
                        'cust_stock_out_head_id' => $this->data['cust_stock_out_head_id'],
                ))
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

    /**
     * หา ProductSerial ตาม cust_stock_out_id
     */
    function json_find_product_serials_by_cust_stock_out_id() {
        $this->RequestHandler->setContent('json');

        $this->ProductSerial->contain();
        $data = $this->ProductSerial->find('all',
                array(
                'conditions' => array(
                        'cust_stock_out_id' => $this->data['cust_stock_out_id'],
                        'cust_stock_out_type' => CustStockOut::STOCK_OUT_TYPE,
                        'is_active_flag' => true, // ยังไม่ได้ return
                ),
                'order' => 'stock_out_priority ASC'
                )
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }
}
?>